<!--
 * createor: zc
 * email: zc8023zs@163.com
 * create_time: 2020/3/14 13:46:24
 *-->
<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.user_name" placeholder="登录名/姓名" style="width: 200px;" class="filter-item" 
        @keyup.enter.native="handleFilter" /> 
        
        <el-button class="filter-item" type="primary" v-show="permissions.p_select" icon="el-icon-search" @click="handleFilter">
          {{ $t('table.search') }}
        </el-button>
        <el-button class="filter-item" style="margin-left: 10px;" v-show="permissions.p_add" type="primary" icon="el-icon-edit" @click="handleCreate">
            {{ $t('table.add') }}
        </el-button> 
    </div>
    <el-table
      :key="tableKey"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column type="index" label=" " width="50" align="center" :index="table_index"></el-table-column>
       <el-table-column v-if="permissions.operation" :label="$t('table.actions')" align="center" width="280" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" v-show="permissions.p_edit" size="mini" @click="handleUpdate(row)">
            {{ $t('table.edit') }}
          </el-button> 
          <el-button type="primary" v-show="permissions.p_pwd" size="mini" @click="handleUpdatePwd(row)"  style="width:80px;">
            设置密码
          </el-button>
          <el-button  size="mini" v-if="row.init_default==0" v-show="permissions.p_del" type="danger" @click="handleDelete(row)">
            {{ $t('table.delete') }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="登录名" align="center" show-overflow-tooltip>
        <template slot-scope="{row}">
          <span>{{ row.user_name }}</span>
        </template>
      </el-table-column> 
      <el-table-column label="姓名" align="center" show-overflow-tooltip>
        <template slot-scope="{row}">
          <span>{{ row.real_name }}</span>
        </template>
      </el-table-column> 
      <el-table-column label="手机号" align="center">
        <template slot-scope="{row}">
          <span>{{ row.mobile }}</span>
        </template>
      </el-table-column> 
      <el-table-column label="部门" align="center" show-overflow-tooltip>
        <template slot-scope="{row}">
          <span>{{ row.dept_name }}</span>
        </template>
      </el-table-column> 
      <el-table-column label="角色" align="center" show-overflow-tooltip>
        <template slot-scope="{row}">
          <span>{{ row.role_name }}</span>
        </template>
      </el-table-column> 
      <!-- <el-table-column label="状态" align="center">
        <template slot-scope="{row}">
          <span>{{ row.status }}</span>
        </template>
      </el-table-column>  -->
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.size" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :close-on-click-modal='false' :visible.sync="dialogFormVisible" append-to-body>
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px" >
        <el-form-item label="登录名" prop="user_name">
          <input type="hidden" v-model="temp.id" />
          <el-input maxlength="21" v-model.trim="temp.user_name" />
        </el-form-item>   
        <el-form-item label="姓名" prop="real_name">
          <el-input maxlength="21" v-model.trim="temp.real_name" />
        </el-form-item>   
        <el-form-item label="手机号码"  prop="mobile">
          <el-input v-model="temp.mobile" maxlength='12' />
        </el-form-item> 
        <el-form-item label="所属部门" prop="dept_id">
         <treeselect
              :options="deptTreeData"
              :default-expand-level="1"
              placeholder="请选择所属部门"
              v-model="temp.dept_id"
              :normalizer="normalizer"
            />
        </el-form-item> 
        <el-form-item label="所属角色" prop="role_id"> 
          <el-select v-model="temp.role_id" placeholder="请选择角色" value-key="id">
            <el-option
              v-for="item in roles"
              :key="item.id"
              :label="item.role_name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item> 
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t('table.cancel') }}
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          {{ $t('table.confirm') }}
        </el-button>
      </div>
    </el-dialog> 

    <el-dialog title="设置密码" :close-on-click-modal='false' :visible.sync="dialogUpdatePwd" append-to-body>
      <el-form ref="pwdForm" :rules="rules" :model="temp_pwd" label-position="left" label-width="100px" >
        <el-form-item label="密码" prop="password">
          <el-input v-model="temp_pwd.password" type="password" />
        </el-form-item> 
        <el-form-item label="确认密码" prop="repassword">
          <el-input v-model="temp_pwd.repassword" type="password" />
        </el-form-item>     
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogUpdatePwd = false">
          {{ $t('table.cancel') }}
        </el-button>
        <el-button type="primary" @click="updatePwdData">
          {{ $t('table.confirm') }}
        </el-button>
      </div>
    </el-dialog> 
  </div>
</template>

<script>
import { fetchList, fetchObj, createObj, updateObj, getDeptTree, getRoles, deleteObj, updatePwd } from '@/api/project/system/project_sys_sys_user'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { Loading } from 'element-ui';
// import the component
import treeselect from "@riophae/vue-treeselect";
// import the styles
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: 'a_systema_sys_user',
  components: { Pagination,treeselect },
  filters: {
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0, 
      listQuery: {
        page: 1,
        size: 20,
        user_name: ''
      }, 
      permissions:{
        p_select:false,
        p_add:false,
        p_edit: false,
        p_del: false,
        p_pwd: false,
        operation: false,
      },
      temp: {
        id: 0,
        user_name: '',
        real_name: '',
        mobile: '',
        dept_id: null,
        dept_name: '',
        role_id: null
      },
      temp_pwd:{
        password: '',
        repassword: '',
        id: 0
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加'
      }, 
      rules: {
        user_name: [{ required: true, message: '登录名必填', trigger: 'change' },
        { type: "string", max: 20, message: "登录名不超过20个字", trigger: "blur"} 
        ],
        real_name: [{ required: true, message: '姓名必填', trigger: 'change' },
        { type: "string", max: 20, message: "姓名不超过20个字", trigger: "blur"} ],
        mobile: [{ required: true, message: '手机号必填', trigger: 'change' },
         {
            pattern: /^1(3|4|5|6|7|8|9)\d{9}$/,
            message: "请输入正确的手机号",
            trigger: "blur"
          }],
        dept_id: [{ required: true, message: '部门必选', trigger: 'change' }],
        role_id: [{ required: true, message: '角色必选', trigger: 'change' }],
        password: [
          { required: true, message: '密码必填', trigger: 'change' },
          {type: "string",max: 100,message: "密码不超过100个字符",trigger: "blur"},
          {pattern: /^(?!.*[\s])/,message: "密码不能有空格",trigger: "change"}
        ],
        repassword: [
          { required: true, message: '确认密码必填', trigger: 'change' },
          {type: "string",max: 100,message: "密码不超过100个字符",trigger: "blur"},
          {pattern: /^(?!.*[\s])/,message: "密码不能有空格",trigger: "change"}
        ]
      },  
      deptTreeData: null,
      roles: null,
      dialogUpdatePwd: false
    }
  },
  created() {
    this.getList()
    this.getRoles()
    this.getTree()
    this.$per(result=>{ 
      this.permissions.p_select=result['*/system/sysuser/getSysUserList']!=null;
      this.permissions.p_add=result['*/system/sysuser/addSysUser']!=null;
      this.permissions.p_edit=result['*/system/sysuser/updateSysUser']!=null;
      this.permissions.p_del=result['*/system/sysuser/deleteSysUser']!=null;
      this.permissions.p_pwd=result['*/system/sysuser/changePsd']!=null;

      if(result['*/system/sysuser/updateSysUser']!=null 
        || result['*/system/sysuser/deleteSysUser']!=null 
          || result['*/system/sysuser/changePsd']!=null){
            this.permissions.operation=true;
      }
    })
  },
  methods: {
    table_index(index) {
      return (
        (this.listQuery.page - 1) * this.listQuery.size +
        index +
        1
      );
    },
    openFullScreen() {
        const loading = this.$loading({
          lock: true,
          text: '数据处理中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.2)'
        }); 
        setTimeout(() => {
          loading.close();
        }, 2000);
    },
     normalizer(node) {
      if (node.children == undefined || node.children == null || node.children.length==0) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.dept_name,
        children: node.children
      };
    },
    getList() { 
      fetchList(this.listQuery).then(response => {
        this.list = response.dataArray.dataList;
        this.total = response.dataArray.dataCount;
      })
    }, 
    getRoles(uid){ 
      getRoles(uid).then(response => {
        this.roles = response.dataArray.dataList;
      })
    },
    getTree(uid){ 
      getDeptTree(uid).then(response => {
        this.deptTreeData = response.dataArray.dataList;
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    }, 
    resetTemp() {
      this.temp = {
        id: 0,
        user_name: '',
        real_name: '',
        mobile: '',
        dept_id: null,
        dept_name: '',
        role_id: null
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.roles=[];
      this.deptTreeData=[];
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        this.getRoles();
        this.getTree();
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) { 
          this.openFullScreen();
          createObj(this.temp).then(res => { 
            this.handleFilter();
            this.dialogFormVisible = false
            if (res.code == 0) {
              this.$notify({
                title: "成功",
                message: res.msg,
                type: "success",
                duration: 2000
              });
            }else{
              this.$notify({
                title: "失败",
                message: res.msg,
                type: "error",
                duration: 2000
              });
            }
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      if(this.temp.dept_id==0 || this.temp.dept_id=='' || this.temp.dept_id==undefined){
        this.temp.dept_id=null;
      } 
      this.roles=[];
      this.deptTreeData=[];
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        this.getRoles(this.temp.id);
        this.getTree(this.temp.id);
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.openFullScreen();
          const tempData = Object.assign({}, this.temp) 
          updateObj(tempData).then(res => { 
            this.handleFilter();
            this.dialogFormVisible = false
            if (res.code == 0) {
              this.$notify({
                title: "成功",
                message: res.msg,
                type: "success",
                duration: 2000
              });
            }else{
              this.$notify({
                title: "失败",
                message: res.msg,
                type: "error",
                duration: 2000
              });
            }
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('确定删除该用户？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
       this.openFullScreen();
        deleteObj(row).then(res=>{
          this.handleFilter();
          if (res.code == 0) {
              this.$notify({
                title: "成功",
                message: res.msg,
                type: "success",
                duration: 2000
              });
            }else{
              this.$notify({
                title: "失败",
                message: res.msg,
                type: "error",
                duration: 2000
              });
            }
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },
    handleUpdatePwd(row){
      this.temp_pwd={
        id: row.id,
        password: '',
        repassword: ''
      };
      this.dialogUpdatePwd = true; 
    },
    updatePwdData(){
      this.$refs['pwdForm'].validate((valid) => {
        if(this.temp_pwd.password!=this.temp_pwd.repassword){
          this.$notify({
              title: '失败',
              message: '两次输入密码不一致',
              type: 'error',
              duration: 2000
            })
            valid=false;
        }
        if (valid) {
          this.openFullScreen();
          const tempData = Object.assign({}, this.temp_pwd) 
          updatePwd(tempData).then(() => { 
            this.handleFilter();
            this.dialogUpdatePwd = false
            this.$notify({
              title: '成功',
              message: '设置成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    }
  }
}
</script>
